package models;

import static util.FindFoodUtil.empty;

import javax.persistence.Column;
import javax.persistence.Entity;

import play.cache.Cache;
import play.db.jpa.Model;
import util.GoogleGeocode;
import util.FindFoodUtil;
import util.GoogleGeocode.GeocodeException;

import com.javadocmd.simplelatlng.LatLng;

@Entity
public class ZipcodeGeo extends Model {

	public static ZipcodeGeo get(String zipcode) throws GeocodeException {
		if (zipcode == null || !zipcode.matches("[0-9]{5}"))
			return null;

		ZipcodeGeo zipgeo = Cache.get("zip-" + zipcode, ZipcodeGeo.class);
		if (zipgeo == null) {
			zipgeo = ZipcodeGeo.find("byZipcode", zipcode).first();
			if (zipgeo == null) {
				LatLng latLng = new GoogleGeocode("US", "postal_code")
						.geocode(zipcode);
				if (latLng != null) {
					zipgeo = new ZipcodeGeo(zipcode, latLng);
					zipgeo.save();
				}
			}

			if (zipgeo != null) {
				Cache.set("zip-" + zipcode, zipgeo);
			}
		}
		return zipgeo;
	}

	@Column(unique = true, nullable = false)
	private String zipcode;
	@Column(nullable = false)
	private Double latitude;
	@Column(nullable = false)
	private Double longitude;

	public ZipcodeGeo(String zipcode) {
		this.zipcode = zipcode;
	}

	public ZipcodeGeo(String zipcode, LatLng latLng) {
		this(zipcode);
		this.latitude = latLng.getLatitude();
		this.longitude = latLng.getLongitude();
	}

	public String getZipcode() {
		return zipcode;
	}

	public LatLng getLatLng() {
		if (latitude == null || longitude == null)
			return null;
		return new LatLng(latitude, longitude);
	}
}
